package com.hframe.http.client;

import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;

/**
 * Created by heqian on 12/7/16.
 */
public class FileParam extends KeyParam {
    private ArrayList<Disposition> files = new ArrayList<>();

    public FileParam() {
    }

    public FileParam(File file) {
        addFile(file, "file", "file");
    }

    public void addFile(File file) {
        addFile(file, "file", "file");
    }

    public void addFile(File file, String contentType, String name) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("--").append(BOUNDARY).append("\r\n");
        buffer.append("Content-Disposition: from-data; title=\"").append(name).append("\"; filename=\"").append(file.getName()).append("\"\r\n");
        buffer.append("Content-Type: ").append(contentType).append("/").append(file.getParent()).append("\r\n");
        buffer.append("\r\n");

        Disposition disposition = new Disposition();
        disposition.dis = buffer.toString().getBytes();
        disposition.file = file;
        files.add(disposition);
    }

    @Override
    public void init(HttpURLConnection conn) {
        contentType = "multipart/from-data; boundary=" + BOUNDARY;
        conn.setRequestProperty("Content-type", contentType);
    }

    @Override
    public long getDataLenght() {
        long lenght = super.getDataLenght();
        for (Disposition item : files) {
            lenght += item.dis.length + item.file.length();
        }

        return lenght;
    }


    @Override
    public boolean read(HttpURLConnection connection, Write write) throws Exception {
        super.read(connection, write);
        FileInputStream in = null;
        for (Disposition item : files) {
            writeBuffer(write, item.dis);

            try {
                in = new FileInputStream(item.file);
                byte[] buffer = new byte[4096];
                int lenght = 0;
                while ((lenght = in.read(buffer)) > 0) {
                    write.write(buffer, 0, lenght);
                }

                byte[] linend = "\r\n".getBytes("utf-8");
                write.write(linend, 0, linend.length);
            } finally {
                if (in != null)
                    in.close();
            }
        }
        byte[] linend = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
        write.write(linend, 0, linend.length);
        return true;
    }

    class Disposition {
        private byte[] dis = null;
        private File file = null;
    }

}
